<script setup lang="ts">
  import { ref, onMounted } from "vue"

  interface Props {
    resizeConf: {
      width: number
      widthRange: number[]
    }
  }
  const props = withDefaults(defineProps<Props>(), {
    resizeConf: () =>({
      width: 200, // 初始宽度
      widthRange: [100, 500] // 宽度范围
    })
  })

  onMounted(() => {
    dragControllerDiv(resize, resizeHandle)
  })

  const resize = ref()
  const resizeHandle = ref()
  const dragControllerDiv = function(resizeBox, resizeHandle) {
    resizeBox.value.style.width = props.resizeConf.width + 'px'
    // 鼠标按下事件
    resizeHandle.value.onmousedown = e => {
      const resizeWidth = resizeBox.value.offsetWidth
      // 水平坐标
      const startX = e.clientX
      // 鼠标拖动事件
      document.onmousemove = ev => {
        const moveX = ev.clientX
        const moveLen = resizeWidth + (moveX - startX)
        if (props.resizeConf.widthRange[0] <= moveLen && props.resizeConf.widthRange[1] >= moveLen) {
          resizeBox.value.style.width = moveLen + 'px'
        }
      }
      // 鼠标松开事件
      document.onmouseup = function() {
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }

</script>

<template>
  <div ref="resize" class="resize">
    <div ref="resizeHandle" class="handle-resize" />
    <slot />
  </div>
</template>

<style scoped>
  .resize {
    background: #fbfbfb;
    position: relative;
    word-wrap: break-word;
    height: 100%;
    .handle-resize {
      cursor: col-resize;
      position: absolute;
      right: -5px;
      width: 6px;
      height: 50px;
      border-left: 2px solid #656565;
      border-right: 2px solid #676767;
      top: calc(50% - 25px);
      z-index: 9;
    }
  }
</style>